<template>
  <div class="map" id="map"></div>
  <div class="btns">
    <div>zoom: {{ zoom }} </div>
    <button @click="show">显示</button>
    <button @click="hide">隐藏</button>
  </div>
</template>

<script setup>

import * as L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import './utils/Leaflet.canvaslabel'
import HelloWorld from './components/HelloWorld.vue'
// import './utils/leaflet.canvas-markers'
import { computed, onMounted, ref, createVNode, render } from 'vue'
// import VueSvg from './assets/vue.svg'
import './utils/L.LabelTextCollision'
// import {CanvasLabel} from "@panzhiyue/leaflet-canvaslabel"
// import {CanvasMarkerLayer} from "@panzhiyue/leaflet-canvasmarker"
import 'leaflet-rotatedmarker'
import './utils/leaflet.contextmenu'
import { LeafletDrawLonlatLine } from "leaflet-lonlat-gridlines";
import './utils/Control.MiniMap'
import 'leaflet.boatmarker'
import 'leaflet.marker.highlight'


// let zoom = computed(() => {
//   if(map) {
//     return map.getZoom()
//   }
//   return 
// })
const zoom = ref()
let lonLatGridLines
onMounted(() => {

  //矢量文本标签渲染器
  var canvasLabel = new L.CanvasLabel({
    defaultLabelStyle: {
      collisionFlg: true,
      scale: 1,
      // strokeStyle: "white",
      strokeStyle: "#fff",
      fillStyle: "rgba(0,0,0,1)",
      lineWidth: 3,

    }
  })

  window.map = L.map('map', {
    center: [23, 118], // 地图中心
    crs: L.CRS.EPSG4326,
    zoom: 6,
    minZoom: 1,
    maxZoom: 15,
    //限制显示地理范围
    maxBounds: L.latLngBounds(L.latLng(-180, -180), L.latLng(180, 180)),
    // renderer : canvasLabel,
    contextmenu: true, //右键菜单
    logoControl: false, // 隐藏logo版权
    zoomControl: false, // 缩放控件
    attributionControl: false // 隐藏文字版权
  })
  addLayer()
  function addLayer() {
    // 矢量图+注记
    let mapTypes = ['vec_c', 'cva_c'];
    // 天地图 token
    let tdtToken = 'ce62df9dd155c78d0d3a96652168cc71';
    let layers = [];
    for (let i = 0, len = mapTypes.length; i < len; i++) {
      let tdtUrl = `http://t0.tianditu.gov.cn/DataServer?T=${mapTypes[i]}&x={x}&y={y}&l={z}&tk=${tdtToken}`;
      let layer = L.tileLayer(tdtUrl, {
        zoomOffset: 1,// 注意如果是 web 墨卡托投影(EPSG:3857) 请改为 0
        noWrap: true,
        bounds: [[-90, -180], [90, 180]]
      });
      layers.push(layer);
    }
    // LayerGroup 对象
    let tdtLayerGroup = L.layerGroup(layers).addTo(map);
    // 获取地图 id，可用于获取地图对象
    let leafletId = tdtLayerGroup._leaflet_id;
  }
  const CustomDivOverlay = L.DivOverlay.extend({
  _update: function() {
    if (!this._map) {
      return;
    }
    // 更新弹出层的内容和位置
    // 例如，可以使用 this.getElement() 获取弹出层的 DOM 元素，然后修改其内容或样式
    const element = this.getElement();
    element.innerHTML = 'Hello, World!';
    // 更新位置
    const latlng = this._latlng;
    const pos = this._map.latLngToLayerPoint(latlng);
    L.DomUtil.setPosition(element, pos);
  },
  
  _initLayout: function() {
    // 初始化弹出层的布局
    // 例如，可以通过 L.DomUtil.create 创建一个包含内容的容器，并将容器添加到弹出层的 DOM 元素中
    const container = L.DomUtil.create('div', 'custom-div');
    container.innerHTML = '<h3>Custom DivOverlay</h3>';
    // const element = this.getElement();  
    marker.getElement().appendChild(container);
    // element.appendChild(container);
  }
  });
  // const customOverlay = new CustomDivOverlay();
  // customOverlay.setLatLng(L.latLng(23, 118)); // 设置弹出层的位置
  // customOverlay.addTo(map);

  // L.tileLayer(
  //   // "http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}",
  //   "http://t0.tianditu.gov.cn/img_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=ce62df9dd155c78d0d3a96652168cc71"
  // ).addTo(map);



  //添加经纬网
  //  /** 创建经纬线网格绘制对象*/
  //  lonLatGridLines = new LeafletDrawLonlatLine(map);
  // /** 初始化话的时候，触发一次绘制*/
  // lonLatGridLines.drawLonlatTileGrid();
  // /** 添加绘制地图事件（即拖动地图时，清除上一次的图层的同时绘制新的图层）*/
  // lonLatGridLines.addDrawEvent();  

  //添加海事图
  // var seaUrl = "http://tiles.openseamap.org/seamark/{z}/{x}/{y}.png";
  // var osmUrl = "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png";
  // var sea = L.tileLayer(seaUrl, { subdomains: ["a", "b", "c"] }).addTo(map);
  // var OpenStreetMap = L.tileLayer(osmUrl, { subdomains: ["a", "b", "c"] }).addTo(map);


  // let osmUrl = 'http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}'
  // var osm2 = new L.TileLayer(osmUrl, {minZoom: 1, maxZoom: 15 });
  // var miniMap = new L.Control.MiniMap(osm2, {
  //     toggleDisplay: true,   // 是否显示最小化按钮
  //     width: 250, // 鹰眼图宽度
  //     height: 150, // 鹰眼图高度
  //     strings: {
  //       hideText: '隐藏',
  //       showText: '显示'
  //     }
  //   }).addTo(map);
  // init()

  // map.on('moveend', function (e) {
  //   reset()
  // })
  // 创建自定义辅助菜单
  var contextMenu = L.popup({
    offset: [10, 230],
    className: 'menuName',
    maxWidth: '100%',
    // autoPanPadding: [20,20]
  });
  let div = document.createElement('div')
  // document.body.appendChild(div)
  let Vnode = createVNode(HelloWorld, {
    closeFN: close
  })
  let d = render(Vnode, div)
  // // console.log(d,'d')
  // console.log(div,'div')
  // console.log(Vnode,'Vnode')
  // 定义锁定样式和隐藏样式
  const lockedStyle = {
    color: 'red',
    opacity: 1,
  };

  const hiddenStyle = {
    color: 'transparent',
    opacity: 0,
  };



  let myIcon
  // // 创建标记并添加到地图上
  var marker = L.marker([23, 113], { highlight: 'temporary' }).addTo(map).on('contextmenu', e => {
    // 阻止默认的右键菜单
    e.originalEvent.preventDefault();
    // 设置菜单内容和位置
    contextMenu.setLatLng(e.latlng)
      .setContent(div)
      .openOn(map);


    // // 创建工具提示
    // const tooltip = L.tooltip({
    //   permanent: true,
    //   direction: 'right',
    //   offset: [5, 0],
    //   className: 'custom-tooltip',
    // }).setContent(div);

    // // 绑定工具提示到标记上
    // marker.bindTooltip(tooltip).openTooltip();
    // setTimeout(() => {
    //   console.log(1111)
    //   marker.closeTooltip()
    // }, 2000)
  }).on('mouseover', function (e) {
    const customDiv = document.createElement('div');
customDiv.id = 'myCustomDiv';
customDiv.innerHTML = 'This is my custom div';
    const container = L.DomUtil.create('div', 'custom-div');
    container.innerHTML = '<h3>Custom DivOverlay</h3>';
    // const element = this.getElement();  
    marker.getElement().appendChild(container);

      // 创建并添加 <div> 元素
      // const div = document.createElement('div');
      // div.className = 'hehe'
      // div.innerText = 'Hello, World!';
      
      // // 在标记容器中附加 <div> 元素
      // marker.getElement().appendChild(div);
    // marker.setStyle(lockedStyle);
  }).on('mouseout', e => {
    // 更新标记样式为隐藏样式

  })






  // .on('contextmenu', (e) => {
  //   // 阻止默认的右键菜单
  //     e.originalEvent.preventDefault();
  //     // 设置菜单内容和位置
  //     contextMenu.setLatLng(e.latlng)
  //     .setContent(div)
  //     .openOn(map);
  // })

  function close() {
    contextMenu.close()
  }


  // // 监听地图上的 contextmenu 事件
  // map.on('contextmenu', function(e) {
  //   // 阻止默认的右键菜单
  //   e.originalEvent.preventDefault();

  //   // 设置菜单内容和位置
  //   contextMenu.setLatLng(e.latlng)
  //     .setContent('<p>Custom Menu</p><ul><li>Option 1</li><li>Option 2</li></ul>')
  //     .openOn(map);
  // });

})

let iconSvg = `
  <svg xmlns="http:www.w3.org/2000/svg" width="12" height="20" viewBox="0 0 22.655 40.216">
    <g transform="translate(-20149.595 -10363.793)">
        <line style="
      stroke: #000;
      stroke-linecap: square;
      stroke-width: 1.92px;
      stroke-miterlimit: 10;
        fill : #50a7a1; opacity : undefined; fill-opacity : undefined"  class="a" x1="11.906" transform="translate(20159.594 10365.067)"/>
        <path style="
      stroke: #000;
      stroke-miterlimit: 10;
      stroke-linecap: round;
      stroke-width: 1.98px;
        fill : #50a7a1; opacity : undefined; fill-opacity : undefined" class="b" d="M671.149,627.737h-16.5v-31.8l8.25-6.7,8.25,6.7Z" transform="translate(19495.695 9775.521)"/>
    </g>
  </svg>  
`
let markers = [];
let labels = []
var icon = L.divIcon({
  html: iconSvg,
  rotationAngle: 45,
  className: '',
  iconSize: [20, 20],
  // iconAnchor: [10, 9]
});

//2、引入文件
// var icon = L.icon({
//   iconUrl: VueSvg ,
//   rotationAngle: 45,
//   iconSize: [20, 18],
//   iconAnchor: [10, 9]
// });


function init() {
  removeLayer()
  for (let i = 0; i < 300; i++) {
    let d = getRandomLatLng(map)
    var marker = L.marker(d, {
      icon: icon,
      rotationAngle: Math.random() * 180,
      contextmenu: true,
      contextmenuInheritItems: false,
      contextmenuItems: [
        {
          text: '显示坐标',
          callback: showCoordinates,
          contextmenuItems: [
            {
              text: '作为地图中心',
              callback: centerMap
            },
          ]
        },

        {
          text: '作为地图中心',
          callback: centerMap
        },
        '-', {
          text: '地图放大',
          // icon: './images/zoom-in.png',
          callback: zoomIn
        }, {
          text: '地图缩小',
          // icon: './images/zoom-out.png',
          callback: zoomOut
        }
      ],
    })
      // .bindTooltip('某某船'+ i, {
      //   className: 'typhname-tooltip',
      //   direction: 'right', // 向右
      //   opacity: 0.7 ,
      //   offset: L.point(10, 0), // 偏移
      //   permanent: true // 永久提示
      // }).openTooltip()
      .addTo(map)
    markers.push(marker)

    let label = L.circleMarker(d,
      {
        color: 'transparent',
        fillColor: 'transparent',
        // opacity: 0,
        radius: 0,
        labelStyle: {
          rotation: 0,
          minZoom: 4,
          defaultHeight: 30,
          text: '某某船' + i,
          offsetX: 20,
          offsetY: 20,
        }
      }
    ).addTo(map)
    labels.push(label)
  }
}

function showCoordinates(e) {
  alert(e.latlng);
}

function centerMap(e) {
  map.panTo(e.latlng);
}

function zoomIn(e) {
  map.zoomIn();
}

function zoomOut(e) {
  map.zoomOut();
}

function removeLayer() {
  if (markers.length == 0) return
  for (var i = 0; i < markers.length; i++) {
    var marker = markers[i];
    let label = labels[i]
    map.removeLayer(label);
    map.removeLayer(marker);
  }
  labels = []
  markers = []
}
function reset() {
  var bounds = map.getBounds();
  let mapZoom = map.getZoom();
  zoom.value = mapZoom
  for (var i = 0; i < markers.length; i++) {
    var marker = markers[i];
    var markerLatLng = marker.getLatLng();
    if (mapZoom <= 3) {
      map.removeLayer(marker);
      continue
    }
    // 检查标记是否在可视范围内
    if (bounds.contains(markerLatLng)) {
      // 在可视范围内，进行渲染操作 
      marker.addTo(map);
    } else {
      // 不在可视范围内，移除标记
      map.removeLayer(marker);
    }
  }
}


const show = () => {
  // init()
  /** 初始化话的时候，触发一次绘制*/
  lonLatGridLines.drawLonlatTileGrid();
  /** 添加绘制地图事件（即拖动地图时，清除上一次的图层的同时绘制新的图层）*/
  lonLatGridLines.addDrawEvent();
}
const hide = () => {
  // removeLayer()
  lonLatGridLines.removeDrawEvent()
}

//生成随机点
const getRandomLatLng = map => {
  let bounds = map.getBounds(),
    southWest = bounds.getSouthWest(),
    northEast = bounds.getNorthEast(),
    lngSpan = northEast.lng - southWest.lng,
    latSpan = northEast.lat - southWest.lat;

  return L.latLng(
    southWest.lat + latSpan * Math.random(),
    southWest.lng + lngSpan * Math.random()
  );
}
</script>

<style>
@import url('./utils/leaflet.contextmenu.css');
@import url('./utils/Control.MiniMap.css');

.map {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

.btns {
  position: absolute;
  left: 200px;
  top: 200px;
  z-index: 99;
}

.menuName {
  .leaflet-popup-tip {
    display: none;
  }

  .leaflet-popup-content {
    margin: 0;
  }
}
</style>